Genere un modelo de esta base de datos: [ID] int IDENTIDAD (1,1) NO NULO , [Prenume] nvarchar (100) NULL , [Nume] nvarchar (100) NULL ALTER TABLE [voluntari] AÑADIR RESTRICCIÓN [PK_voluntari] CLAVE PRIMARIA ([ID]); VAMOS CREAR ÍNDICE ÚNICO [UQ__voluntari__0000000000000042] ON [voluntari] ([NrLeg] ASC); VAMOS Las clases generadas son: voluntari público parcial de clase { public int ID {obtener; conjunto; } cadena pública Prenume {get; conjunto; } cadena pública Nume {get; conjunto; } } y ValuntariEntities de clase parcial pública: DbContext { ValuntariEntities públicos () : base ("nombre = ValuntariEntities") { } anulación protegida void OnModelCreating (DbModelBuilder modelBuilder) { lanzar nueva UnintentionalCodeFirstException (); } public DbSetvoluntaris {get; conjunto; } } El código utilizado para insertar un objeto en la base de datos es: Gestiune_Voluntari.ValuntariEntities ve = new ValuntariEntities (); voluntari v = nuevo voluntari (); v.Nume = "Ion"; v.Prenume = "ion"; ve.voluntaris.Add (v); ve.SaveChanges (); En la tabla de la base de datos solo puedo insertar un objeto. Si ejecuto el código anterior, solo funciona una vez, si intento insertar otros valores, no funciona y obtengo este error: Se produjo un error al actualizar las entradas. Consulte la excepción interna para obtener más detalles. en System.Data.Entity.Internal.InternalContext.SaveChanges () en System.Data.Entity.Internal.LazyInternalContext.SaveChanges () en System.Data.Entity.DbContext.SaveChanges () en Gestiune_Voluntari.MainWindow.Button_Click (Object sender, RoutedEventArgs e) en c: \ Users \ Florin \ Documents \ Proiecte programare \ Gestiunevoluntari \ Gestiune Voluntari \ Gestiune Voluntari \ MainWindow.xaml.cs: línea 35 en System.Windows.RoutedEventHandlerInfo.InvokeHandler (destino de objeto, RoutedEventArgs routedEventArgs) en System.Windows.EventRoute.InvokeHandlersImpl (origen del objeto, argumentos RoutedEventArgs, booleano reRaised) en System.Windows.UIElement.RaiseEventImpl (DependencyObject sender, RoutedEventArgs args) en System.Windows.UIElement.RaiseEvent (RoutedEventArgs e) en System.Windows.Controls.Primitives.ButtonBase.OnClick () en System.Windows.Controls.Button.OnClick () en System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp (MouseButtonEventArgs e) en System.Windows.UIElement.OnMouseLeftButtonUpThunk (remitente del objeto, MouseButtonEventArgs e) en System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler (Delegate genericHandler, Object genericTarget) en System.Windows.RoutedEventArgs.InvokeHandler (controlador delegado, destino de objeto) en System.Windows.RoutedEventHandlerInfo.InvokeHandler (destino de objeto, RoutedEventArgs routedEventArgs) en System.Windows.EventRoute.InvokeHandlersImpl (origen del objeto, argumentos RoutedEventArgs, booleano reRaised) en System.Windows.UIElement.ReRaiseEventAs (DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent) en System.Windows.UIElement.OnMouseUpThunk (remitente del objeto, MouseButtonEventArgs e) en System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler (Delegate genericHandler, Object genericTarget) en System.Windows.RoutedEventArgs.InvokeHandler (controlador delegado, destino de objeto) en System.Windows.RoutedEventHandlerInfo.InvokeHandler (destino de objeto, RoutedEventArgs routedEventArgs) en System.Windows.EventRoute.InvokeHandlersImpl (origen del objeto, argumentos RoutedEventArgs, booleano reRaised) en System.Windows.UIElement.RaiseEventImpl (DependencyObject sender, RoutedEventArgs args) en System.Windows.UIElement.RaiseTrustedEvent (argumentos de RoutedEventArgs) en System.Windows.UIElement.RaiseEvent (argumentos de RoutedEventArgs, booleano confiable) en System.Windows.Input.InputManager.ProcessStagingArea () en System.Windows.Input.InputManager.ProcessInput (entrada InputEventArgs) en System.Windows.Input.InputProviderSite.ReportInput (InputReport inputReport) en System.Windows.Interop.HwndMouseInputProvider.ReportInput (IntPtr hwnd, modo InputMode, marca de tiempo Int32, acciones RawMouseActions, Int32 x, Int32 y, rueda Int32) en System.Windows.Interop.HwndMouseInputProvider.FilterMessage (IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean y manejado) en System.Windows.Interop.HwndSource.InputFilterMessage (IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean y manejado) en MS.Win32.HwndWrapper.WndProc (IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, booleano y manejado) en MS.Win32.HwndSubclass.DispatcherCallbackOperation (Objeto o) en System.Windows.Threading.ExceptionWrapper.InternalRealCall (devolución de llamada de delegado, argumentos de objeto, int32 numArgs) en MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen (fuente del objeto, método delegado, argumentos del objeto, numArgs de Int32, catchHandler delegado) en System.Windows.Threading.Dispatcher.LegacyInvokeImpl (prioridad DispatcherPriority, TimeSpan timeout, método Delegate, Object args, Int32 numArgs) en MS.Win32.HwndSubclass.SubclassWndProc (IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam) en MS.Win32.UnsafeNativeMethods.DispatchMessage (MSG & msg) en System.Windows.Threading.Dispatcher.PushFrameImpl (DispatcherFramecuadro) en System.Windows.Threading.Dispatcher.PushFrame (marco DispatcherFrame) en System.Windows.Threading.Dispatcher.Run () en System.Windows.Application.RunDispatcher (ignorar el objeto) en System.Windows.Application.RunInternal (ventana de la ventana) en System.Windows.Application.Run (ventana de la ventana) en System.Windows.Application.Run () en Gestiune_Voluntari.App.Main () en c: \ Users \ Florin \ Documents \ Proiecte programare \ Gestiunevoluntari \ Gestiune Voluntari \ Gestiune Voluntari \ obj \ Debug \ App.g.cs: línea 0 en System.AppDomain._nExecuteAssembly (ensamblado RuntimeAssembly, String [] args) en System.AppDomain.ExecuteAssembly (String assemblyFile, Evidence assemblySecurity, String [] args) en Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly () en System.Threading.ThreadHelper.ThreadStart_Context (estado del objeto) en System.Threading.ExecutionContext.RunInternal (ExecutionContext executionContext, devolución de llamada ContextCallback, estado del objeto, boolean preserveSyncCtx) en System.Threading.ExecutionContext.Run (ExecutionContext executionContext, devolución de llamada ContextCallback, estado del objeto, boolean preserveSyncCtx) en System.Threading.ExecutionContext.Run (ExecutionContext executionContext, devolución de llamada ContextCallback, estado del objeto) en System.Threading.ThreadHelper.ThreadStart () La excepción interna es: No se puede insertar un valor duplicado en un índice único. [Nombre de tabla = voluntari, Nombre de restricción = UQ__voluntari__0000000000000042] la fuente es: Proveedor de datos SQL Server Compact ADO.NET No funciona incluso si especifico manualmente una ID para el objeto que no se usa en la tabla. El único caso en el que funciona es cuando la tabla está vacía. ¡Gracias! ACTUALIZAR: El problema fue otra columna que se estableció como clave única. Olvidé eso.
2021-01-30 08:18:27
Creo que el problema radica en su base de datos debido a esta línea: [ID] int IDENTIDAD (1,1) NO NULO Esperaría que fuera: [ID] int IDENTIDAD Con el (1,1) es posible que esté llamando a la IDENTIDAD (función) en lugar de la propiedad IDENTIDAD | Tu respuesta StackExchange.ifUsing ("editor", function () { StackExchange.using ("editor externo", función () { StackExchange.using ("fragmentos", función () { StackExchange.snippets.init (); }); }); }, "fragmentos de código"); StackExchange.ready (function () { var channelOptions = { etiquetas: "" .split (""), id: "1" }; initTagRenderer ("". split (""), "" .split (""), channelOptions); StackExchange.using ("editor externo", función () { // Debe activar el editor después de los fragmentos, si los fragmentos están habilitados if (StackExchange.settings.snippets.snippetsEnabled) { StackExchange.using ("fragmentos", función () { createEditor (); }); } else { createEditor (); } }); function createEditor () { StackExchange.prepareEditor ({ useStacksEditor: false, heartbeatType: 'respuesta', autoActivateHeartbeat: falso, convertImagesToLinks: verdadero, noModals: cierto, showLowRepImageUploadWarning: true, reputacionToPostImages: 10, bindNavPrevention: verdadero, sufijo: "", imageUploader: { brandingHtml: "Desarrollado por \ u003ca href = \" https: //imgur.com/ \ "\ u003e \ u003csvg class = \" svg-icon \ "width = \" 50 \ "height = \" 18 \ "viewBox = \ "0 0 50 18 \" fill = \ "none \" xmlns = \ "http: //www.w3.org/2000/svg \" \ u003e \ u003cpath d = \ "M46.1709 9.17788C46.1709 8.26454 46.2665 7.94324 47.1084 7.58816C47.4091 7.46349 47.7169 7.36433 48.0099 7.26993C48.9099 6.97997 49.672 6.73443 49.672 5.93063C49.672 5.22043 48.9832 4.61182 48.1414 4.61182C47.4335 4.61182 46.725645.40531 43.1481 6.59048V11.9512C43.1481 13.2535 43.6264 13.8962 44.6595 13.8962C45.6924 13.8962 46.1709 13.2535 46.1709 11.9512V9.17788Z \ "/ \ u003e \ u003cpath d = \" M32.492 10.1419C32.492 14.648.942348 41.5985 12.6954 41.5985 10.1419V6.59049C41.5985 5.28821 41.1394 4.66232 40.1061 4.66232C39.0732 4.66232 38.5948 5.28821 38.5948 6.59049V9.60062C38.5948 10.8521 38.2696 11.5455 37.0451 11.5454.5C35.8 3520.49455C35.8 521 35.4954 9.60062V6.59049C35.4954 5.28821 35.0173 4.66232 34.0034 4.66232C32.9703 4.66232 32.492 5.28821 32.492 6.59049V10.1419Z \ "/ \ u003e \ u003cpath fill-rule = \" evenodd \ "clip-rule = \" evenodd \ "d = \ "M25.6622 17.6335C27.8049 17.6335 29.3739 16.9402 30.2537 15.6379C30.8468 14.7755 30.9615 13.5579 30.9615 11.9512V6.59049C30.9615 5.28821 30.4833 4.66231 29.4502 4.66231C28.9913 4.662025C 289.15527 .1369 4.56087 21.0134 6.57349 21.0134 9.27932C21.0134 11.9852 23.003 13.913 25.3754 13.913C26.5612 13.913 27.4607 13.4902 28.1109 12.6616C28.1109 12.7229 28.1161 12.7799 28.121 12.8346C834.232.283 28.121 12.8346C2834.125.283 28.121 12.8346C2834.1256.28 15.2321 24.1352 14.9821 23.5661 14.7787C23.176 14.6393 22.8472 14.5218 22.5437 14.5218C21.7977 14.5218 21.2429 15.0123 21.2429 15.6887C21.2429 16.7375 22.9072 17.6335 25.6622 17.6317.10.99 732.943C 27.2119 7.09766 28.0918 7.94324 28.0918 9.27932C28.0918 10.6321 27.2311 11.5116 26.1024 11.5116C24.9737 11.5116 24.1317 10.6491 24.1317 9.27932Z \ "/ \ u003e \ u003cpath d = \" M16.802802.86.9512C358. 19.8079 13.2535 19.8079 11.9512V8.12928C19.8079 5.82936 18.4879 4.62866 16.4027 4.62866C15.1594 4.62866 14.279 4.98375 13.3609 5.88013C12.653 5.05154 11.6581 4.62866 10.3573 4.62866C9.34336 4.62866 4,62866 780793 4,8993 5.00066 5.28821 5.00066 6.59049V11.9512C5.00066 13.2535 5.47873 13.8962 6.51203 13.8962C7.54479 13.8962 8.0232 13.2535 8.0232 11.9512V8.90741C8.0232 7.58817 8.44431 6.91179 9.53458 6.91179C10.593V 9.91179 9.53458 6.91179C10.51093 6.9411811 C13.4375 13.8962 13.9157 13.2535 13.9157 11.9512V8.90741C13.9157 7.58817 14.3365 6.91179 15.4269 6.91179C16.4027 6.91179 16.8045 7.58817 16.8045 8.94108V11.9512Z \ "/ \ u003e \ u003cpath d = \ "M3.31675 6.59049C3.31675 5.28821 2.83866 4.66232 1.82471 4.66232C0.791758 4.66232 0.313354 5.28821 0.313354 6.59049V11.9512C0.313354 13.2535 0.791758 13.8962 1.82471 13.8962C2.8571675 13.8962 1.82471 13.8962C2.8571675 13.8962 3.313354 u003e \ u003cpath d = \ "M1.87209 0.400291C0.843612 0.400291 0 1.1159 0 1.98861C0 2.87869 0.822846 3.57676 1.87209 3.57676C2.90056 3.57676 3.7234 2.87869 3.7234 1.98861C3.7234 1.1159 \ 2.9" # 1. \ "/ \ u003e \ u003c / svg \ u003e \ u003c / a \ u003e", contentPolicyHtml: "Contribuciones de usuario con licencia bajo \ u003ca href = \" https: //stackoverflow.com/help/licensing \ "\ u003ecc by-sa \ u003c / a \ u003e \ u003cahref = \ "https: //stackoverflow.com/legal/content-policy \" \ u003e (política de contenido) \ u003c / a \ u003e ", allowUrls: verdadero }, onDemand: verdadero, discardSelector: ".discard-answer" , initialShowMarkdownHelp: true, enableTables: true, enableSnippets: true }); } }); ¡Gracias por contribuir con una respuesta a Stack Overflow! Asegúrese de responder la pregunta. ¡Proporcione detalles y comparta su investigación! Pero evita ... Pedir ayuda, aclaraciones o responder a otras respuestas. Hacer declaraciones basadas en opiniones; respóndelos con referencias o experiencia personal. Para obtener más información, consulte nuestros consejos sobre cómo escribir buenas respuestas. Borrador guardado Borrador descartado Regístrate o inicia sesión StackExchange.ready (function () { StackExchange.helpers.onClickDraftSave ('# login-link'); }); Regístrese con Google Registrarse usando Facebook Regístrese con correo electrónico y contraseña Enviar Publicar como invitado Nombre Email Requerido, pero nunca mostrado StackExchange.ready ( function () { StackExchange.openid.initPostLogin ('. New-post-login', 'https% 3a% 2f% 2fstackoverflow.com% 2fquestions% 2f24570706% 2fc-sharp-ef-can-insert-only-one-item% 23new-answer' , 'question_page'); } ); Publicar como invitado Nombre Email Requerido, pero nunca mostrado Publica tu respuesta Descarte Al hacer clic en "Publicar su respuesta", acepta nuestros términos de servicio, política de privacidad y política de cookies. No es la respuesta que estás buscando? Examine otras preguntas etiquetadas c # entity-framework insert sql-server-ce o haga su propia pregunta.